#include "pagedataanalysis.h"
#include "ui_pagedataanalysis.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include <QMessageBox>
#include <QValueAxis>
#include <QDateTimeAxis>

pageDataAnalysis::pageDataAnalysis(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::pageDataAnalysis),
    m_dataAnalysis(new DataAnalysis(this)),
    m_alertManager(new AlertManager(this)),
    m_chart(new QChart()),
    m_temperatureSeries(new QLineSeries()),
    m_humiditySeries(new QLineSeries()),
    m_axisX(new QDateTimeAxis()),
    m_axisY(new QValueAxis()),
    m_dataMonitor(new DataMonitor(this))
{
    ui->setupUi(this);

    // 初始化图表
    setupChart();

    // 设置时间范围默认值
    ui->startDateTime->setDateTime(QDateTime::currentDateTime().addDays(-7));
    ui->endDateTime->setDateTime(QDateTime::currentDateTime());

    // 连接信号槽
    connect(m_alertManager, &AlertManager::dataUpdated, this, &pageDataAnalysis::updateAlertTable);
    loadAlarmData();
}

pageDataAnalysis::~pageDataAnalysis()
{
    delete ui;
    delete m_chart;
}

void pageDataAnalysis::setupChart()
{
    // 配置温度序列
    m_temperatureSeries->setName("温度");
    QPen redPen(Qt::red);
    redPen.setWidth(2);
    m_temperatureSeries->setPen(redPen);

    // 配置湿度序列
    m_humiditySeries->setName("湿度");
    QPen bluePen(Qt::blue);
    bluePen.setWidth(2);
    m_humiditySeries->setPen(bluePen);

    // 添加序列到图表
    m_chart->addSeries(m_temperatureSeries);
    m_chart->addSeries(m_humiditySeries);

    // 配置坐标轴
    m_axisX->setTitleText("时间");
    m_axisX->setFormat("MM-dd hh:mm");
    m_chart->addAxis(m_axisX, Qt::AlignBottom);

    m_axisY->setTitleText("数值");
    m_axisY->setRange(0, 100);
    m_chart->addAxis(m_axisY, Qt::AlignLeft);

    // 绑定坐标轴
    m_temperatureSeries->attachAxis(m_axisX);
    m_temperatureSeries->attachAxis(m_axisY);
    m_humiditySeries->attachAxis(m_axisX);
    m_humiditySeries->attachAxis(m_axisY);

    // 配置图表视图
    ui->chartView->setChart(m_chart);
    ui->chartView->setRenderHint(QPainter::Antialiasing);
}

void pageDataAnalysis::on_btnAnalyze_clicked()
{
    int deviceId = ui->spinDeviceId->value();
    QDateTime start = ui->startDateTime->dateTime();
    QDateTime end = ui->endDateTime->dateTime();

    // 清空旧数据
    m_temperatureSeries->clear();
    m_humiditySeries->clear();

    // 执行分析
    m_dataAnalysis->analyzeData(deviceId, start, end);

    // 查询数据用于图表
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("SELECT timestamp, temperature, humidity FROM data "
                  "WHERE device_id = ? AND timestamp BETWEEN ? AND ? "
                  "ORDER BY timestamp");
    query.addBindValue(deviceId);
    query.addBindValue(start.toString("yyyy-MM-dd hh:mm:ss"));
    query.addBindValue(end.toString("yyyy-MM-dd hh:mm:ss"));

    if(query.exec()) {
        while(query.next()) {
            QDateTime time = QDateTime::fromString(query.value(0).toString(), "yyyy-MM-dd hh:mm:ss");
            m_temperatureSeries->append(time.toMSecsSinceEpoch(), query.value(1).toDouble());
            m_humiditySeries->append(time.toMSecsSinceEpoch(), query.value(2).toDouble());
        }
        // 更新坐标轴范围
        m_axisX->setRange(start, end);
        m_axisY->setRange(0, 100);
    }
    DatabasePool::instance().releaseConnection(db);

    // 显示统计信息
    QList<QSqlRecord> records = m_dataMonitor->queryHistoricalData(deviceId,
        start.toString("yyyy-MM-dd hh:mm:ss"),
        end.toString("yyyy-MM-dd hh:mm:ss"));
    showStatistics(records);
}

void pageDataAnalysis::showStatistics(const QList<QSqlRecord>& records)
{
    if(records.isEmpty()) return;

    double tempSum = 0, humiditySum = 0;
    double maxTemp = -999, minTemp = 999;
    double maxHumidity = -999, minHumidity = 999;

    foreach(const QSqlRecord &rec, records) {
        double temp = rec.value("temperature").toDouble();
        double humidity = rec.value("humidity").toDouble();

        tempSum += temp;
        humiditySum += humidity;

        if(temp > maxTemp) maxTemp = temp;
        if(temp < minTemp) minTemp = temp;
        if(humidity > maxHumidity) maxHumidity = humidity;
        if(humidity < minHumidity) minHumidity = humidity;
    }

    ui->tableStats->setRowCount(4);
    ui->tableStats->setColumnCount(2);
    ui->tableStats->setHorizontalHeaderLabels({"参数", "数值"});

    QStringList rows = {"平均温度", "温度极差", "平均湿度", "湿度极差"};
    QStringList values = {
        QString::number(tempSum/records.count(), 'f', 1),
        QString::number(maxTemp - minTemp, 'f', 1),
        QString::number(humiditySum/records.count(), 'f', 1),
        QString::number(maxHumidity - minHumidity, 'f', 1)
    };

    for(int i=0; i<4; i++){
        ui->tableStats->setItem(i, 0, new QTableWidgetItem(rows[i]));
        ui->tableStats->setItem(i, 1, new QTableWidgetItem(values[i]));
    }
}

void pageDataAnalysis::loadAlarmData()
{
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.exec("SELECT timestamp, content, status FROM alarm_records ORDER BY timestamp DESC LIMIT 50");

    ui->tableAlarms->setColumnCount(3);
    ui->tableAlarms->setHorizontalHeaderLabels({"时间", "告警内容", "状态"});
    ui->tableAlarms->setRowCount(0);

    int row = 0;
    while(query.next()) {
        ui->tableAlarms->insertRow(row);
        ui->tableAlarms->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableAlarms->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableAlarms->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
        row++;
    }
    DatabasePool::instance().releaseConnection(db);
}

void pageDataAnalysis::on_btnGenerateReport_clicked()
{
    int deviceId = ui->spinDeviceId->value();
    QDateTime start = ui->startDateTime->dateTime();
    QDateTime end = ui->endDateTime->dateTime();

    // 生成PDF报告
    m_dataAnalysis->generateTrendGraphAndReport(deviceId, start, end);
    QMessageBox::information(this, "报告生成", "数据分析报告已生成！");
}

void pageDataAnalysis::updateAlertTable()
{
    loadAlarmData();
}
